// packageA/pages/approve/leaveRecord/leaveRecord.js
const app = getApp();
import CommonService from '../../../../utils/service/commonService.js';
const util = require('../../../../utils/util');
import Base64 from '../../../../utils/Base64';
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
import PersonnelManager from '../../../../utils/service/PersonnelManager'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 记录列表
        recordList: [],
        // 是否还有更多数据
        haveMore: true,
        // 当前页码
        page: 1,
        // 每页展示x条
        pageSize: 10,
        // 当前登录用户
        user: null,
        // 当前操作元素X坐标
        xCoordinate: 0,
        // 当前操作元素下标
        touchIndex: 0,
        // 按钮宽度(px)
        butWidth: 80,
        // 姓名
        searchValue:"",
         //项目名称
        projectName:'全部',
         //项目id
        projectId:-1,
    },

      //搜索项目
  onChangeProjectVal(e){
    this.setData({
      valueSearchProject: e.detail
    })
    this.getProjectList();
  },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            //当前登录用户
            user: app.globalData.userInfo,
        });
        this.getRecordList();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },
    onSearch(){
      this.refreshListAndPage();
    },

      //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      page:1,
      notMore: true,
      showNothing: false,
      recordList:[],
    })
    this.getRecordList();
  },

      //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value,
    })
  },

 //显示项目
 onShowProject(){
  this.setData({
    showProject: true
  })
  this.getProjectList();
},

  //隐藏项目
  onCloseProject(){
    this.setData({
      showProject: false,
      valueSearchProject:''
    })
  },
   //确认项目
   onConfirmProject(e){
    this.setData({
      projectId:e.detail.value.id,
      projectName:e.detail.value.text
    })
    this.onCloseProject();
    this.refreshListAndPage();
  },

//查询项目
getProjectList(){
  this.setData({
    projectList: []
  })

  let param = {
    isAuth: true,
    className: 'depart',
    data: {
      searchAll: true,
      isProject:true,
      selectFields: ['id','name']
    }
  }

  //模糊查询
  if(this.data.valueSearchProject){
    param.data.name='%' + this.data.valueSearchProject + '%';
  }

  CommonService.goFindList(param).then(res=>{
    if(res.data.data && res.data.data.result && res.data.data.result.length){
      let result=res.data.data.result;
      let arr=[];
      arr.push({
        text:"全部",
        id:-1
      }); 
      result.forEach(item => {
        arr.push({
          text:item.name,
          id:item.id
        });
      });

      this.setData({
        projectList: arr
      })
    }
  }).catch((error) => {
  })
},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        if (this.data.haveMore) {
            this.setData({
                page: this.data.page + 1
            })
            this.getRecordList();
        } else {
            this.noMoer();
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    /**
     * 没有更多信息时显示提示信息
     * @author Man Yang
     * @date 07/18/2025
     */
    noMoer() {
        wx.showToast({
            title: '没有更多记录了',
            mask: true,
            duration: 3000,
            icon: "error",
            success: (res) => {},
            fail: (res) => {},
            complete: (res) => {},
        })
    },

    /**
     * 获取请假记录列表
     * @author Man Yang
     * @date 07/18/2025
     */
    getRecordList() {
        // 显示加载提示
        wx.showLoading({
            title: '加载中...',
            mask: true // 防止触摸穿透
        });

        let params = {
            isAuth: true,
            className: 'personLeaveRecord',
            data: {
                selectFields: ["id", "project", "applicant", "leaveType", "leaveStartTime", "leaveEndTime", "company", "operator", "createTime","expired","stopTime","leaveReason"],
                //nbl: Base64.encode(util.timeFormatDay(new Date())),
                sort: {
                    id: -1
                },
                page: {
                    page: this.data.page,
                    pageSize: this.data.pageSize,
                }
            }
        }

            //模糊查询
          if(this.data.searchValue){
            let applicant = "applicant.name"
            params.data[applicant] = this.data.searchValue;
          }

          if(this.data.projectId!=null && this.data.projectId!=-1){
            let project = "project.id"
            params.data[project] = this.data.projectId;
          }
          
          console.log(params);
          CommonService.goFindList(params).then(res => {
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result;
                console.log('子菜单列表');
                console.log(result);
                 let list = []
                // this.data.recordList.forEach(r => {
                //     list.push(r);
                // });
                result.forEach(r => {
                    var stateStr = "请假中"
                    if (r.expired&&r.stopTime==null){
                      stateStr = "清洁结束"
                    }else if(r.expired&&r.stopTime!=null){
                      stateStr = "提前结束"
                    }
                    list.push({
                        id: r.id,
                        project: r.project,
                        applicant: r.applicant,
                        leaveType: r.leaveType,
                        leaveStartTime: r.leaveStartTime,
                        leaveEndTime: r.leaveEndTime,
                        company: r.company,
                        operator: r.operator,
                        expired:r.expired,
                        stopTime:r.stopTime,
                        leaveReason:r.leaveReason,
                        createTime: r.createTime.split(" ")[0],
                    });
                });
                // console.log(list);
                this.setData({
                  recordList: this.data.recordList.concat(list)
                })
            } else {
                this.setData({
                    haveMore: false,
                });
                this.noMoer();
            }
        }).catch((error) => {
            console.error(error);
        }).finally(() => {
            // 手动关闭（通常在请求完成时调用）
            wx.hideLoading();
        });

    },

    /**
     * 滑动时触发事件
     * 当跨度宽度等于按钮宽度时，记录该坐标
     * @param {event} e 
     */
    onMove(e) {
        if (Math.abs(e.detail.x) === (this.data.butWidth * 2)) {
            this.setData({
                [`recordList[${e.currentTarget.dataset.index}].x`]: e.detail.x,
            });
        }

        this.setData({
            xCoordinate: e.detail.x,
            touchIndex: e.currentTarget.dataset.index,
        });
    },

    /**
     * 滑动结束时判断若滑出宽度小于1个按钮宽度则收回
     * @author Man Yang
     * @date 07/18/2025
     */
    onTouchEnd() {
        if (Math.abs(this.data.xCoordinate) < this.data.butWidth) {
            this.setData({
                [`recordList[${this.data.touchIndex}].x`]: 0
            });
        }
    },

    /**
     * 终止请假
     * @param {event} e
     * @author Bi Yanshuai
     * @date 08/07/2025 
     */
    onStop(e){
      const id = e.currentTarget.dataset.id;
      const index = e.currentTarget.dataset.index;
      const staffId = e.currentTarget.dataset.item.applicant.id;
      const expired = e.currentTarget.dataset.item.expired;
      console.log(id);
      console.log(staffId);
      console.log(index);
      console.log(e);

      const leaveEndTime = new Date(e.currentTarget.dataset.item.leaveEndTime.replace(/-/g, '/'));
      const now = new Date();
      console.log(leaveEndTime);
      console.log(leaveEndTime.getTime());
      console.log(now);
      console.log(now.getTime());

      if (expired){
        this.setData({
          [`recordList[${index}].x`]: 0
         });
        Toast.fail({
          duration: 5000,
          message: '当前请假信息已经失效，无需终止'
        });   
        return
      }

      if (now.getTime()>leaveEndTime.getTime()){
        console.log("当前时间大于请假结束时间");
        this.setData({
          [`recordList[${index}].x`]: 0
         });
        Toast.fail({
          duration: 5000,
          message: '当前时间已超过请假结束时间，无需进行终止操作哦'
        });   
        return
      }

      Dialog.confirm({
        message: '确定要终止当前请假吗？',
    }).then(() => {
      let param = {
        className: 'personLeaveRecord',
        data: {
          id:id,
          stopTime:util.timeFormat(new Date()),
          expired:true
        }
      }
      console.log(param);
      CommonService.goSave(param).then(res => {
        if (res.statusCode == 200 && res.data.success == true) {
            Toast.success('成功');
            //回调函数，修改员工状态
            let data = {
              staffId:staffId
            }
            PersonnelManager.stopForLeave(data).then(res => {})
            setTimeout(() => {
                this.setData({
                    recordList: []
                });
                //返回列表页并刷新数据
                this.getRecordList();
                this.backAndRefresh();
            }, 1000);
        } else if (res.statusCode == 202) {
            Toast.fail('您操作太快了,请勿重复操作');
        } else {
            Toast.fail('操作失败');
        }
        }).catch((error) => {
            Toast.fail('操作失败');
        });
        //恢复位置
        this.setData({
            [`recordList[${index}].x`]: 0
        });
    }).catch(() => {
            // on cancel
            // 恢复位置
            this.setData({
                [`recordList[${index}].x`]: 0
            });
        });
    },

    backAndRefresh(){
      let pages = getCurrentPages();
      let prevPage = pages[pages.length - 2];
      wx.navigateBack();
    },
    /**
     * 删除记录
     * @param {event} e
     * @author Man Yang
     * @date 07/18/2025 
     */
    onDelete(e) {
        const id = e.currentTarget.dataset.id;
        const index = e.currentTarget.dataset.index;
        const staffId = e.currentTarget.dataset.item.applicant.id;
        Dialog.confirm({
            message: '确定要删除当前记录吗？',
        }).then(() => {
            // on confirm
            let param = {
                className: 'personLeaveRecord',
                data: {
                    id: id,
                    validState: 0,
                }
            }
            console.log(param);
            console.log(staffId);
            CommonService.goSave(param).then(res => {
                if (res.statusCode == 200 && res.data.success == true) {
                    Toast.success('成功');

                      //回调函数，修改员工状态
                      let data = {
                        staffId:staffId
                      }
                      PersonnelManager.stopForLeave(data).then(res => {})
                    setTimeout(() => {
                        this.setData({
                            recordList: []
                        });
                        //返回列表页并刷新数据
                        this.getRecordList();
                    }, 1000);
                } else if (res.statusCode == 202) {
                    Toast.fail('您操作太快了,请勿重复操作');
                } else {
                    Toast.fail('操作失败');
                }
            }).catch((error) => {
                Toast.fail('操作失败');
            });
            // 恢复位置
            this.setData({
                [`recordList[${index}].x`]: 0
            });
        }).catch(() => {
            // on cancel
            // 恢复位置
            this.setData({
                [`recordList[${index}].x`]: 0
            });
        });
    },

    /**
     * 点击内容区域是，位置还原
     * @param {event} e 
     * @author Man Yang
     * @date 07/18/2025
     */
    clickContent(e) {
        if (Math.abs(this.data.recordList[e.currentTarget.dataset.index].x) > 0) {
            this.setData({
                [`recordList[${e.currentTarget.dataset.index}].x`]: 0,
            })
        }
    },

})